import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-19
 * Time: 20:19
 */

//构造好一个Message类,这个类要与JSON格式的key要进行对应
//访问修饰权限是public的,要么就提供getter方法
//因为对JSON字符串进行解析的时候要按照Message这个类进行解析
class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageWallServlet extends HttpServlet {
    //使用objectMapper类对JSON字符串进行解析
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> messageList = new ArrayList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //前端那边已经构造好请求发送给后端服务器这边
        //后端这边就要接收请求,对请求进行解析,返回响应ok
        //使用ObjectMapper类的readValue方法对其进行解析返回给message对象
        //第一个参数是要从请求中读取数据-->使用流对象
        //第二个参数是类对象,解析的JSON字符串按照Message类进行解析
        //JSON解析成对象返回给message里
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        //将客户端的请求保存起来
        //messageList.add(message);
        save(message);
        //这里打印一下message对象的日志
        System.out.println("message : "+ message);
        //成功解析请求并保存起来,接下来要给客户端那边返回接收请求成功的响应
        resp.getWriter().write("{ok:1}");
    }

    //接下来要实现客户端这边要从后端服务器这边拿数据
    //后端服务器这边就要把之前保存在messageList的信息按照JSON字符串的格式返回给客户端那边
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json charset=utf8");
        //将messageList转化成JSON格式的字符串
        List<Message> messageList = load();
        String respString = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respString);
    }

    //使用save方法将数据保存到数据库里面
    private void save(Message message){
        //先与数据库建立连接
        Connection connection =null;
        PreparedStatement statement = null;
        try {
            //与数据库建立连接
            connection = DBUtil.getConnection();
            //构造sql语句--->插入3条记录
            String sql = "insert into message values(?,?,?)";
            //使用PreparedStatement对象将sql发送给数据库
            statement = connection.prepareStatement(sql);
            //填入SQL
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //执行SQL
            int n = statement.executeUpdate();
            if(n!=1){
                System.out.println("插入失败");
            }else {
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            DBUtil.close(connection,statement,null);
        }
    }
    //通过查询数据库里面的记录来返回给客户端
    private List<Message> load(){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> messageList = new ArrayList<>();
        try {
            //与数据库建立好连接
            connection = DBUtil.getConnection();
            //构造好sql语句
            String sql = "select * from message";
            //将sql发送给数据库
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            //执行sql语句
            while(resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }
}
